<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>我的好友</span>
          <div>
            <el-button type="primary" @click="openAddFriendDialog">添加好友</el-button>
            <el-button type="info" @click="goToRequests">
              好友请求
              <el-badge v-if="requestCount > 0" :value="requestCount" class="item" />
            </el-button>
          </div>
        </div>
      </template>

      <el-input
        v-model="searchText"
        placeholder="搜索好友..."
        prefix-icon="Search"
        clearable
        style="margin-bottom: 20px"
      />

      <el-empty v-if="friendList.length === 0" description="暂无好友" />

      <div v-else class="friend-list">
        <el-row :gutter="20">
          <el-col
            v-for="friend in filteredFriends"
            :key="friend.id"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
          >
            <el-card class="friend-card" shadow="hover">
              <div class="friend-info">
                <div class="avatar-container">
                  <el-avatar :size="64" :src="friend.avatar">
                    <img
                      src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
                    />
                  </el-avatar>
                  <div
                    :class="['status-dot', friend.status]"
                    :title="statusText[friend.status]"
                  ></div>
                </div>
                <div class="friend-details">
                  <div class="friend-name">{{ friend.nickname || friend.username }}</div>
                  <div class="friend-status">{{ statusText[friend.status] }}</div>
                  <div v-if="friend.status === 'offline'" class="last-online">
                    上次在线: {{ formatTime(friend.lastOnlineTime) }}
                  </div>
                </div>
                <div v-if="friend.unreadCount > 0" class="unread-badge">
                  <el-badge :value="friend.unreadCount" type="danger" />
                </div>
              </div>
              <div class="friend-actions">
                <el-button type="primary" @click="startChat(friend)">发送消息</el-button>
                <el-dropdown trigger="click" @command="handleCommand($event, friend)">
                  <el-button type="info">
                    操作
                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="viewProfile">查看资料</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>
                        <span style="color: #f56c6c">删除好友</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 添加好友对话框 -->
    <el-dialog v-model="addFriendDialogVisible" title="添加好友" width="500px">
      <el-form
        ref="addFriendFormRef"
        :model="addFriendForm"
        :rules="addFriendRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFriendForm.username" placeholder="请输入用户名、ID或邮箱" />
        </el-form-item>
        <el-form-item label="验证消息" prop="message">
          <el-input
            v-model="addFriendForm.message"
            type="textarea"
            :rows="3"
            placeholder="请输入验证消息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addFriendDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddFriend">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="删除好友" width="400px">
      <span>确定要删除好友 "{{ currentFriend?.nickname || currentFriend?.username }}" 吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ArrowDown } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import type { FriendInfo } from "@/types/social";

const router = useRouter();
const friendList = ref<FriendInfo[]>([
  {
    id: 1,
    userId: 101,
    username: "zhang_san",
    nickname: "张三",
    avatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    status: "online",
    unreadCount: 3,
    lastOnlineTime: "",
    online: true,
  },
  {
    id: 2,
    userId: 102,
    username: "li_si",
    nickname: "李四",
    avatar: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
    status: "busy",
    unreadCount: 0,
    lastOnlineTime: "",
    online: true,
  },
  {
    id: 3,
    userId: 103,
    username: "wang_wu",
    nickname: "王五",
    avatar: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
    status: "offline",
    unreadCount: 0,
    lastOnlineTime: "2023-05-20T15:30:00Z",
    online: false,
  },
  {
    id: 4,
    userId: 104,
    username: "zhao_liu",
    nickname: "赵六",
    avatar: "https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg",
    status: "online",
    unreadCount: 8,
    lastOnlineTime: "",
    online: true,
  },
  {
    id: 5,
    userId: 105,
    username: "sun_qi",
    nickname: "孙七",
    avatar: "https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png",
    status: "offline",
    unreadCount: 0,
    lastOnlineTime: "2023-05-21T09:15:00Z",
    online: false,
  },
]);
const searchText = ref("");
const requestCount = ref(3);
const addFriendDialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const currentFriend = ref<FriendInfo | null>(null);

const addFriendFormRef = ref<FormInstance>();
const addFriendForm = ref({
  username: "",
  message: "我是你的好友，请通过我的好友申请~",
});

const addFriendRules = ref<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  message: [
    { required: true, message: "请输入验证消息", trigger: "blur" },
    { max: 100, message: "最多100个字符", trigger: "blur" },
  ],
});

const statusText = {
  online: "在线",
  offline: "离线",
  busy: "忙碌",
};

const filteredFriends = computed(() => {
  if (!searchText.value) return friendList.value;
  const search = searchText.value.toLowerCase();
  return friendList.value.filter(
    (friend) =>
      friend.username.toLowerCase().includes(search) ||
      (friend.nickname && friend.nickname.toLowerCase().includes(search))
  );
});

// 获取好友列表 - 模拟数据，不再从API获取
const loadFriendList = async () => {
  // 已经有模拟数据了，不需要加载
};

// 获取好友请求数量 - 模拟数据
const loadRequestCount = async () => {
  // 使用模拟的固定值
  requestCount.value = 3;
};

// 打开添加好友对话框
const openAddFriendDialog = () => {
  addFriendDialogVisible.value = true;
  addFriendForm.value = {
    username: "",
    message: "我是你的好友，请通过我的好友申请~",
  };
};

// 提交添加好友
const submitAddFriend = async () => {
  if (!addFriendFormRef.value) return;

  await addFriendFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 模拟添加好友
        ElMessage.success("好友请求已发送");
        addFriendDialogVisible.value = false;
      } catch (error) {
        console.error("发送好友请求失败:", error);
        ElMessage.error("发送好友请求失败，请稍后重试");
      }
    }
  });
};

// 开始聊天
const startChat = (friend: FriendInfo) => {
  router.push(`/social/index`);
  // 在localStorage中设置选中的好友ID
  localStorage.setItem("selectedFriendId", friend.id.toString());
};

// 前往好友请求页面
const goToRequests = () => {
  router.push("/social/index");
  // 设置标记打开好友请求对话框
  localStorage.setItem("openFriendRequests", "true");
};

// 处理下拉菜单命令
const handleCommand = (command: string, friend: FriendInfo) => {
  if (command === "viewProfile") {
    router.push(`/userinfo/index/${friend.userId}`);
  } else if (command === "delete") {
    currentFriend.value = friend;
    deleteDialogVisible.value = true;
  }
};

// 确认删除好友
const confirmDelete = async () => {
  if (!currentFriend.value) return;

  try {
    // 模拟删除好友
    const index = friendList.value.findIndex((f) => f.id === currentFriend.value!.id);
    if (index !== -1) {
      friendList.value.splice(index, 1);
    }

    ElMessage.success("删除成功");
    deleteDialogVisible.value = false;
  } catch (error) {
    console.error("删除好友失败:", error);
    ElMessage.error("删除好友失败，请稍后重试");
  }
};

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return "";
  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  // 小于1天
  if (diff < 86400000) {
    return date.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" });
  }
  // 小于7天
  else if (diff < 604800000) {
    const days = ["日", "一", "二", "三", "四", "五", "六"];
    return `周${days[date.getDay()]} ${date.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" })}`;
  }
  // 大于7天
  else {
    return date.toLocaleDateString("zh-CN", {
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  }
};

onMounted(() => {
  loadFriendList();
  loadRequestCount();
});
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.friend-list {
  margin-top: 20px;
}

.friend-card {
  margin-bottom: 20px;
  border-radius: 8px;

  .friend-info {
    display: flex;
    align-items: center;
    position: relative;
    margin-bottom: 15px;

    .avatar-container {
      position: relative;
      margin-right: 15px;

      .status-dot {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        border: 2px solid #fff;

        &.online {
          background-color: #67c23a;
        }

        &.offline {
          background-color: #909399;
        }

        &.busy {
          background-color: #e6a23c;
        }
      }
    }

    .friend-details {
      flex: 1;

      .friend-name {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 4px;
      }

      .friend-status {
        font-size: 13px;
        color: #606266;
      }

      .last-online {
        font-size: 12px;
        color: #909399;
        margin-top: 2px;
      }
    }

    .unread-badge {
      position: absolute;
      top: 0;
      right: 0;
    }
  }

  .friend-actions {
    display: flex;
    justify-content: space-between;

    .el-button {
      flex: 1;
      margin-right: 10px;

      &:last-child {
        margin-right: 0;
      }
    }
  }
}
</style>
